<template>
  <div style="padding: 0 17px">
    <Breadcrumb/>
    <div style="display: flex;margin-top: 20px;">
      <el-button type="primary" style="margin-right: 15px" @click="addItem">新增
      </el-button>
      <el-select
          v-model="selectedRole"
          placeholder="选择角色进行搜索"
          @change="load"
          style="width: 200px;margin-right: 15px"
      >
      <el-option
          v-for="item in roleOptions"
          :key="item.id"
          :label="item.rolename"
          :value="item.id"
      />
      </el-select>
      <span style="min-width: 200px;margin-right: 15px">
          <OrganizationTree
              @change="load"
              v-model="selectedOrganizationId"
              @tree-select-changed="treeSelectChanged"
          />
      </span>

      <el-input v-model="search" placeholder="请输入用户名、手机号"
                style="width: 200px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
      <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;" @click="load">搜索
      </el-button>
      <el-button type="success" style="" @click="importData">导入</el-button>
      <el-button type="success" style="" @click="exportData">导出</el-button>
    </div>
    <div>
    <el-table :data="tableData" :row-style="{ height: '77px' }" border style="width: calc(100vw - 240px);height: 70vh;margin-top: 20px;font-size: 15px;">
      <el-table-column prop="id" label="ID" width="100"/>
      <el-table-column prop="username" label="用户名" width="150"/>
      <!--<el-table-column prop="clientNames" label="监管单位" width="150"/>-->
      <el-table-column prop="telephone" label="手机号" width="150"/>
      <el-table-column prop="isOnline" label="是否在线" align="center" width="90">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.isOnline === '0'">在线</el-tag>
          <el-tag type="warning" v-else-if="scope.row.isOnline === '1'">离线</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="onlineWay" label="在线方式" width="150"/>
      <el-table-column prop="supervisionTime" label="监管时长(小时)" width="150"/>
      <el-table-column prop="safeResponMan" label="安全责任人" width="150"/>
      <el-table-column prop="safeManager" label="安全管理人" width="150"/>
      <el-table-column prop="safeTelephone" label="负责人电话" width="150"/>
      <el-table-column prop="state" label="状态" width="80">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.state === '0'">正常</el-tag>
          <el-tag type="danger" v-else-if="scope.row.state === '1'">锁定</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="rolename" label="角色" width="150"/>
      <el-table-column prop="organizationName" label="组织" width="200"/>
      <el-table-column prop="clientIds" label="监管单位" width="200">
        <template v-slot="scope">
          <el-tag v-for="tag in scope.row.clientIds" :key="tag" size="small">{{ getTagByKey(this.clientOptions, tag) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="configure" label="顶部配置" width="150"/>
      <el-table-column prop="createTime" label="创建时间" width="150"/>
      <el-table-column prop="email" label="邮箱" width="150"/>
      <el-table-column prop="appkey" label="appkey" width="150"/>
      <el-table-column prop="secret" label="secret" width="150"/>
      <el-table-column prop="url" label="url" width="150"/>
      <!--<el-table-column prop="isSmsReceiv" label="短信接收通知" align="center" width="90">-->
        <!--<template #default="scope">-->
          <!--<el-tag v-if="scope.row.isSmsReceiv === '0'">是</el-tag>-->
          <!--<el-tag v-else-if="scope.row.isSmsReceiv === '1'">否</el-tag>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <!--<el-table-column prop="isTelReceiv" label="电话接收通知" align="center" width="90">-->
        <!--<template #default="scope">-->
          <!--<el-tag v-if="scope.row.isTelReceiv === '0'">是</el-tag>-->
          <!--<el-tag v-else-if="scope.row.isTelReceiv === '1'">否</el-tag>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column align="option" label="操作" fixed="right" width="280">
        <template v-slot="scope">
          <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
          <el-button v-if="this.userInformation.role === 1"  :disabled="scope.row.id===1" type="danger" size="small" icon="Delete" @click="deleteItem(scope.row.id)">删除</el-button>
          <el-button type="primary" size="small" icon="Edit" @click="resetPWD(scope.row.id)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :background="true"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    </div>
    <el-dialog :close-on-click-modal="false" title="用户操作" v-model="operationItemDialog" :show-close="false" width="700">
      <el-form label-position="top" :inline="true" :model="form" ref="form" :rules="rules">
        <el-form-item label="用户名&nbsp;&nbsp;&nbsp;&nbsp;" prop="username">
          <el-input placeholder="请输入用户名" v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="监管状态" v-if="this.userInformation.id === 1" prop="isAllClient">
          <el-select
                  v-model="form.isAllClient"
                  placeholder="请选择监管状态"
          >
            <el-option
                    v-for="item in isAllClientOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="this.userInformation.id === 1 && form.isAllClient==='1'" label="监管单位" prop="clientIds">
           <ClientTree
               :selected="form.clientIds"
               @visible-change="handleVisibleChange"
                   v-model="form.clientIds"/>
        </el-form-item>
        <el-form-item v-if="this.userInformation.id === 1 && form.isAllClient==='0'" label="组织" prop="organization">
          <OrganizationTree
                  v-model="form.organization"
          />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select
              v-model="form.state"
              placeholder="请选择状态"
          >
            <el-option
                v-for="item in stateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="telephone">
          <el-input placeholder="请输入联系方式" v-model="form.telephone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select
              v-model="form.role"
              placeholder="请选择角色"
          >
            <el-option
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.rolename"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="安全责任人" prop="safeResponMan">
          <el-input placeholder="请输入安全责任人" v-model="form.safeResponMan" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="安全管理人" prop="safeManager">
          <el-input placeholder="请输入安全管理人" v-model="form.safeManager" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="负责人电话" prop="safeTelephone">
          <el-input placeholder="请输入负责人电话" v-model="form.safeTelephone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="顶部配置" prop="configure">
          <el-input placeholder="请输入顶部配置" v-model="form.configure" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="appkey" prop="appkey">
          <el-input placeholder="请输入appkey" v-model="form.appkey" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="secret" prop="secret">
          <el-input placeholder="请输入secret" v-model="form.secret" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="url" prop="url">
          <el-input placeholder="请输入url" v-model="form.url" autocomplete="off"></el-input>
        </el-form-item>
        <!--<el-form-item label="短信接收通知" prop="isSmsReceiv">-->
          <!--<el-select-->
                  <!--v-model="form.isSmsReceiv"-->
                  <!--placeholder="请选择是否短信接收通知"-->
          <!--&gt;-->
            <!--<el-option-->
                    <!--v-for="item in isReceivOptions"-->
                    <!--:key="item.value"-->
                    <!--:label="item.label"-->
                    <!--:value="item.value"-->
            <!--/>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="电话接收通知" prop="isTelReceiv">-->
          <!--<el-select-->
                  <!--v-model="form.isTelReceiv"-->
                  <!--placeholder="请选择是否电话接收通知"-->
          <!--&gt;-->
            <!--<el-option-->
                    <!--v-for="item in isReceivOptions"-->
                    <!--:key="item.value"-->
                    <!--:label="item.label"-->
                    <!--:value="item.value"-->
            <!--/>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset('form')">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导入" v-model="dialogImportVisible" width="520px">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="模板下载:" padding-top:10px>
          <el-button type="primary" size="small" style="" @click="exportTemplate">用户信息</el-button>
        </el-form-item>
        <el-form-item label="文件" padding-top:-20px>
          <el-upload :headers="headers"
                           :multiple="false"
                     :on-success="onUploadSuccess"
                     :on-error="onUploadError"
                     :action="serverIp+'/user/importData'"
                     class="upload-demo">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request.js";
import ClientTree from "@/components/ClientTree.vue";
import OrganizationTree from "@/components/OrganizationTree.vue";
import Breadcrumb from "@/components/Breadcrumb.vue";
import {serverIp} from "../../../public/static/config"

export default {
  name: "User",
  components: {Breadcrumb, OrganizationTree, ClientTree},
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      serverIp,
                headers: {
                    token:  JSON.parse(localStorage.getItem('user')).token,
                },
      dialogImportVisible: false,
      userInformation:JSON.parse(localStorage.getItem("user")),
      stateOptions:[
        {
          value:"0",
          label:"正常"
        },{
        value:"1",
        label:"锁定"
      }],
      isAllClientOptions:[
        {
          value:"0",
          label:"监管全部下级单位"
        },{
          value:"1",
          label:"监管部分下级单位"
        }],
      isReceivOptions:[
        {
          value:"0",
          label:"是"
        },{
          value:"1",
          label:"否"
        }],
      roleOptions:[],
      currentData:{},
      selectedOrganizationId:JSON.parse(localStorage.getItem("user")).organization,
      selectedRole:"",
      search: '',     // 搜索框
      tableData: [],  // 表单
      selectOptionName: '',
      clientOptions:[],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      operationItemDialog: false,  // 弹窗
      form: {},        // 编辑用户信息赋值
      rules: {
        username: [
          {required: true, message: '请输入名称', trigger: 'blur'},
        ],
        isAllClient: [
          {required: true, message: '请选择监管状态', trigger: 'blur'},
        ],
        clientIds: [
          {required: true, message: '请选择监管单位', trigger: 'blur'},
        ],
        organization: [
          {required: true, message: '请选择组织', trigger: 'blur'},
        ],
        role: [
          {required: true, message: '请选择角色', trigger: 'blur'},
        ],
        configure: [
          {required: true, message: '请输入顶部配置', trigger: 'blur'},
        ],
        state: [
          {required: true, message: '请选择状态', trigger: 'blur'},
        ],
        safeResponMan: [
          {required: true, message: '请输入安全责任人', trigger: 'blur'},
        ],
        safeManager: [
          {required: true, message: '请输入安全管理人', trigger: 'blur'},
        ],
        safeTelephone: [
          {required: true, message: '请输入负责人电话', trigger: 'blur'},
        ],
      },
    }
  },
  mounted() {
    // 初始化加载用户数据
    this.load()
    this.getRoleOptions()
    this.getClientOptions()
  },
  methods: {
    getTagByKey(tags, key) {
      for (let i = 0; i < tags.length; i++) {
        if (tags[i].id === key) {
          return tags[i].name;
        }
      }
    },
    handleVisibleChange(visible) {
      // 如果下拉框打开，清空选中的项
      if (visible) {
        this.$nextTick(() => {
          this.form.clientIds = [];  // 清空 form.clientIds
        });
      }
    },
    importData() {
      this.dialogImportVisible = true;
    },
    onUploadSuccess() {
      this.$message.success('上传成功');
      this.dialogImportVisible = false;
      location.reload();
    },
    onUploadError(){
      this.$message.error('上传失败');
    },
    // 模板下载
    exportTemplate() {
      window.location.href = '../xlsx/user.xlsx'
    },
    exportData() {
      let level = JSON.parse(localStorage.getItem("user")).level
      let userId = JSON.parse(localStorage.getItem("user")).id
      if (this.currentData.level!==undefined){
        level=this.currentData.level
      }
      window.open(serverIp + '/user/export?keyWord=' + this.search +
              "&organizationId="+this.selectedOrganizationId+"&role="+this.selectedRole+"&level="+level+"&userId="+userId);
    },
    getClientOptions(){
      let level = JSON.parse(localStorage.getItem("user")).level
      let organizationId = JSON.parse(localStorage.getItem("user")).organization
      let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
      let clientIds;
      if (isAllClient === "1") {
        clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
      } else {
        clientIds = [];
      }
      request.get("/client/listbyName?name="+this.selectOptionName+"&organizationId="+organizationId+"&level="+level+"&isAllClient="+isAllClient+"&clientIds="+clientIds).then(res=>{
        this.clientOptions=res.data
        console.log(this.clientOptions+"未找到------------")
      })
    },
    // 搜索及初始化
    load() {
      let level = JSON.parse(localStorage.getItem("user")).level
      let userId = JSON.parse(localStorage.getItem("user")).id
      if (this.currentData.level!==undefined){
        level=this.currentData.level
      }
      request.get("/user/page?keyWord=" + this.search + "&pageNum=" + this.currentPage + "&pageSize=" + this.pageSize +
                      "&organizationId="+this.selectedOrganizationId+"&role="+this.selectedRole+"&level="+level+"&userId="+userId).then(res => {
        if (res.code === '200') {
          for (let key in res.data) {
            if (key === "record") {
              this.tableData = res.data[key];
            } else if (key === "total") {
              this.total = res.data[key];
            }
          }
        } else {
          this.$message.error("错误" + res.msg)
        }
      })
    },
    // 获取角色
    getRoleOptions(){
      try {
        request.get("/role/all").then(res=>{
          if (res.code === '200'){
            this.roleOptions = res.data
          }else {
            this.$message.error("获取角色错误"+res.msg)
          }
        })
      }catch (e) {
        this.$message.error("获取角色错误"+e)
      }
    },
    // 新增用户
    addItem(){
      this.operationItemDialog = true
    },
    // 编辑用户
    editItem(scope) {
      Object.assign(this.form,scope)
      this.operationItemDialog = true
    },
    // 编辑、新增确定按钮
    submitForm(val) {
      this.$refs[val].validate((valid) => {
        if (valid) {
          request.post("/user/edit", this.form).then(res => {
            if (res.code === '200') {
              this.$message({
                message: "成功",
                type: "success"
              })
              this.load()
              this.reset("form")
            } else {
              this.$message.error("操作失败" + res.msg)
            }
          })
        }
      })
    },
    resetPWD(scope){
      this.$confirm('是否确定重置密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.get("/user/resetPwd?id=" + scope).then(res => {
          if (res.code === '200') {
            this.$notify({
              title: '重置成功',
              message: '用户密码重置成功，当前密码为123456'
            });
          } else {
            this.$message.error("删除失败" + res.msg)
          }
        })
      });
    },
    reset(val) {
      this.operationItemDialog = false;
      this.form = {};
      this.$refs[val].clearValidate();
    },
    // 删除确定弹窗
    deleteItem(scope) {
      this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.get("/user/delete/" + scope).then(res => {
          if (res.code === '200') {
            this.$message("成功")
            this.load()
          } else {
            this.$message.error("删除失败" + res.msg)
          }
        })
      });
    },
    treeSelectChanged(data, node) {
      this.currentData = data
    },
    handleSizeChange(pageSize) {   // 改变当前每页的个数触发
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {  // 改变当前页码触发
      this.currentPage = pageNum
      this.load()
    },
  }
}
</script>

<style scoped>
:deep(.el-table th .cell) {
  font-weight: 700
}
.el-select {
  width: var(--el-form-width);
}
.el-input {
  width: var(--el-form-width);
}
</style>
